package delayqueue

import (
	"encoding/json"
	"github.com/go-basic/uuid"
	"github.com/go-redis/redis"
	"time"
)

// EnqueueData ...
type EnqueueData struct {
	MsgId   string      `json:"msg_id"`
	Message interface{} `json:"message"`
}

// Enqueue ...
func Enqueue(queue string, message interface{}, delayTime time.Duration) (string, error) {
	queue = Config.Namespace + "queue:" + queue
	m := &manager{
		queue: queue,
	}

	data := &EnqueueData{
		MsgId:   uuid.New(),
		Message: message,
	}
	member, err := json.Marshal(data)
	if err != nil {
		return "", err
	}

	score := float64(time.Now().Add(delayTime).UnixNano())
	z := []redis.Z{
		{
			Score:  score,
			Member: member,
		},
	}
	err = m.pushTasks(z)
	if err != nil {
		return "", err
	}

	return data.MsgId, nil
}
